import {
  SET_LIST,
  CHANGE_INPUT_VALUE,
  ADD_ITEM,
  DELETE_ITEM
} from './actionTypes'

const defaultState = {
  inputValue: 'AntDesign',
  list: []
}

export default (state = defaultState, action) => {
  // console.log({ state, action })

  // reducer 里只能接收state，不能改变state
  if (action.type === SET_LIST) {
    let newState = JSON.parse(JSON.stringify(state))
    if (state.list.length > 0) {
      newState.list = [...state.list, ...action.value]
    } else {
      newState.list = action.value
    }

    return newState
  }

  if (action.type === CHANGE_INPUT_VALUE) {
    let newState = JSON.parse(JSON.stringify(state))
    newState.inputValue = action.value
    return newState
  }

  if (action.type === ADD_ITEM) {
    let newState = JSON.parse(JSON.stringify(state))
    newState.list.push(action.value || newState.inputValue)
    newState.inputValue = ''
    return newState
  }

  if (action.type === DELETE_ITEM) {
    let newState = JSON.parse(JSON.stringify(state))
    newState.list.splice(action.index, 1)
    return newState
  }

  return state
}